package com.liit.console.controller.front;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.liit.console.filter.WebContext;
import com.liit.module.entity.Carousel;
import com.liit.module.entity.Files;
import com.liit.module.entity.Template;
import com.liit.module.frame.utils.ConfigUtil;
import com.liit.module.frame.utils.Const;
import com.liit.module.frame.utils.FileUtil;
import com.liit.module.frame.utils.ValidatorUtils;
import com.liit.module.frame.utils.page.Pagination;
import com.liit.module.service.CarouselService;
import com.liit.module.service.FilesService;
import com.liit.module.service.TemplateService;

/**
 * @author dingweibo
 * @Title: CarouselController.java
 * @Description: 首页轮播
 * @date 2015年12月15日
 */
@Controller
@RequestMapping(value = "/carousel")
public class CarouselController {

	private Logger logger = Logger.getLogger(getClass());

	@Resource
	CarouselService carouselService;

	@Resource
	FilesService filesService;

	@Resource
	TemplateService templateService;

	/**
	 * 分页查询轮播图
	 * 
	 * @param carousel
	 * @param pagination
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/list")
	public String list(Carousel carousel, Pagination pagination) throws Exception {
		Map<String, Object> result = carouselService.listPage(pagination, carousel);
		List<Carousel> list = (List<Carousel>) result.get("list");
		BeanUtils.copyProperties(result.get("page"), pagination);
		Map<String, Map<String, Files>> imgMap = new HashMap<String, Map<String, Files>>();
		for (Carousel c : list) {
			Map<String, Files> row = new HashMap<String, Files>();
			Files imgBg = filesService.selectById(c.getImgBg());
			imgBg.setPath(FileUtil.getUrl(imgBg));
			row.put("imgBg", imgBg);

			if (c.getImgLayer() != null) {
				Files imgLayer = filesService.selectById(c.getImgLayer());
				imgLayer.setPath(FileUtil.getUrl(imgLayer));
				row.put("imgLayer", imgLayer);
			}
			imgMap.put(c.getId().toString(), row);
		}
		WebContext.setAttribute("imgMap", imgMap);
		WebContext.setAttribute("list", list);
		WebContext.setAttribute(Const.PAGINATION, pagination);
		return "/front/carouselList";
	}

	/**
	 * 添加轮播图
	 * 
	 * @return
	 */
	@RequestMapping(value = "/add")
	public String add(Integer id) {
		if (id != null) {
			Carousel carousel = carouselService.selectById(id);
			WebContext.setAttribute("carousel", carousel);
			WebContext.setAttribute("imgBgPath", FileUtil.getUrl(filesService.selectById(carousel.getImgBg())));
			if (carousel.getImgLayer() != null) {
				WebContext.setAttribute("imgLayerPath", FileUtil.getUrl(filesService.selectById(carousel.getImgLayer())));
			}
		}
		return "/front/carouselAdd";
	}

	/**
	 * 保存轮播图
	 * 
	 * @param carousel
	 * @param id
	 * @return
	 * @throws IOException
	 * @throws IllegalStateException
	 */
	@RequestMapping("/save")
	public String save(Carousel carousel, @RequestParam("imgBgFile") MultipartFile imgBgFile, @RequestParam("imgLayerFile") MultipartFile imgLayerFile) {
		try {
			// 上传图片
			String path = ConfigUtil.get("file.upload.path") + Const.UPLOAD_PATH_CAROUSEL;
			String newFileName = null;
			int type = 0;
			String fileName = null;
			String ext = null;
			int size = 0;// 图片大小
			String contentType = null;
			Date now = new Date();
			Files filesRecord = null;
			// 背景图
			if (!imgBgFile.isEmpty()) {
				fileName = imgBgFile.getOriginalFilename();
				ext = fileName.substring(fileName.lastIndexOf('.') + 1);
				newFileName = UUID.randomUUID().toString() + "." + ext;
				size = (int) imgBgFile.getSize();
				contentType = imgBgFile.getContentType();
				File targetFile = new File(path, newFileName);
				if (!targetFile.exists()) {
					targetFile.mkdirs();
				}
				imgBgFile.transferTo(targetFile);

				filesRecord = new Files();
				// 删除历史图片
				if (carousel.getImgBg() != null) {
					filesRecord.setId(carousel.getImgBg());
					filesRecord.setStatus(Const.FILES_STATUS_DELETE);
					filesService.updateById(filesRecord);
				}

				filesRecord.setPath(Const.UPLOAD_PATH_CAROUSEL + newFileName);
				filesRecord.setType(type);
				filesRecord.setName(fileName);
				filesRecord.setExt(ext);
				filesRecord.setSize(size);
				filesRecord.setContentType(contentType);
				filesRecord.setSort(0);
				filesRecord.setStatus(Const.FILES_STATUS_INIT);
				filesRecord.setCreateTime(now);
				// 插入图片并得到Files.id
				carousel.setImgBg(filesService.insertAndReturnPK(filesRecord));
			}

			// 浮层
			if (!imgLayerFile.isEmpty()) {
				fileName = imgLayerFile.getOriginalFilename();
				ext = fileName.substring(fileName.lastIndexOf('.') + 1);
				newFileName = UUID.randomUUID().toString() + "." + ext;
				size = (int) imgLayerFile.getSize();
				contentType = imgLayerFile.getContentType();
				File targetFile = new File(path, newFileName);
				if (!targetFile.exists()) {
					targetFile.mkdirs();
				}
				imgLayerFile.transferTo(targetFile);

				filesRecord = new Files();
				// 删除历史图片
				if (carousel.getImgLayer() != null) {
					filesRecord.setId(carousel.getImgLayer());
					filesRecord.setStatus(Const.FILES_STATUS_DELETE);
					filesService.updateById(filesRecord);
				}

				filesRecord.setPath(Const.UPLOAD_PATH_CAROUSEL + newFileName);
				filesRecord.setType(type);
				filesRecord.setName(fileName);
				filesRecord.setExt(ext);
				filesRecord.setSize(size);
				filesRecord.setContentType(contentType);
				filesRecord.setSort(0);
				filesRecord.setStatus(Const.FILES_STATUS_INIT);
				filesRecord.setCreateTime(now);
				// 插入图片并得到Files.id
				carousel.setImgLayer(filesService.insertAndReturnPK(filesRecord));
			}

			String message = ValidatorUtils.validate(carousel);
			if (StringUtils.isBlank(message)) {
				if (carousel.getId() != 0) {
					carousel.setUpdateTime(now);
					carouselService.updateById(carousel);
				} else {
					carousel.setCreateTime(now);
					carousel.setUpdateTime(now);
					carousel.setId(carouselService.insertAndReturnPK(carousel));
				}
				WebContext.setAttribute(Const.MSG, "保存成功");
				WebContext.setAttribute("imgBgPath", FileUtil.getUrl(filesService.selectById(carousel.getImgBg())));
				if (carousel.getImgLayer() != null) {
					WebContext.setAttribute("imgLayerPath", FileUtil.getUrl(filesService.selectById(carousel.getImgLayer())));
				}
			} else {
				WebContext.setAttribute(Const.MSG, message);
			}
		} catch (Exception e) {
			logger.error("保存失败", e);
			WebContext.setAttribute(Const.MSG, "保存失败");
		}
		return "/front/carouselAdd";
	}

	/**
	 * 删除轮播图
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping("/delete")
	@ResponseBody
	public Object delete(@RequestParam Integer id) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put(Const.STATUS, -1);
		Carousel record = carouselService.selectById(id);
		if (record == null) {
			map.put(Const.MSG, "未查到轮播图信息");
			return map;
		}
		int i = filesService.updateStatusByIds(Arrays.asList(record.getImgBg(), record.getImgLayer()), Const.FILES_STATUS_DELETE);// 删除图片
		if (i > 0) {
			i = carouselService.deleteById(id);// 删除轮播图
			if (i > 0) {
				map.put(Const.STATUS, 0);
			}
		}
		return map;
	}

	/**
	 * 删除图片
	 * 
	 * @param id
	 * @param type
	 * @return
	 */
	@RequestMapping("/deleteImg")
	@ResponseBody
	public Object deleteImg(@RequestParam Integer id, @RequestParam Integer fileId) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put(Const.STATUS, -1);
		if (id == null || fileId == null) {
			map.put(Const.MSG, "参数异常");
			return map;
		}
		Carousel record = carouselService.selectById(id);
		if (record == null) {
			map.put(Const.MSG, "未查到轮播图信息");
			return map;
		}
		if (fileId.equals(record.getImgLayer())) {
			record.setImgLayer(null);
		} else {
			map.put(Const.MSG, "删除失败,fileId不存在");
			return map;
		}
		record.setUpdateTime(new Date());
		int i = carouselService.update(record);
		if (i > 0) {
			filesService.updateStatusByIds(Arrays.asList(fileId), Const.FILES_STATUS_DELETE);// 删除轮播图
			map.put(Const.STATUS, 0);
		} else {
			map.put(Const.MSG, "删除失败");
		}
		return map;
	}

	/**
	 * 首页推荐
	 * 
	 * @return
	 */
	@RequestMapping("/recommendAdd")
	public String recommendAdd() {
		Template record = templateService.selectById(3);
		WebContext.setAttribute("template", record);
		return "/front/recommendAdd";
	}

	@RequestMapping(value = "/recommendSave")
	@ResponseBody
	public Object save(Template template) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put(Const.STATUS, -1);
		try {
			String message = ValidatorUtils.validate(template);
			if (StringUtils.isBlank(message)) {
				int i = templateService.updateById(template);
				if (i > 0) {
					map.put(Const.STATUS, 0);
					map.put(Const.MSG, "保存成功");
				}
			} else {
				map.put(Const.MSG, message);
				return map;
			}
		} catch (Exception e) {
			e.printStackTrace();
			map.put(Const.MSG, Const.DEFAULT_ERROR);
		}
		return map;
	}
}
